/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Global Trust Authority is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use common_log::{error, info};
use plugin_manager::{PluginManager, PluginManagerInstance, ServiceHostFunctions, ServicePlugin};

use crate::{
    chain::attestation_chain::{AttestationHandler, AttestationContext},
    entities::attest_request::Evidence,
    error::attestation_error::AttestationError,
};

/// Handler for verifying evidence in the attestation chain
pub struct EvidenceVerificationHandler {
    next: Option<Box<dyn AttestationHandler>>,
}

impl EvidenceVerificationHandler {
    pub fn new() -> Self {
        Self {
            next: None,
        }
    }

    /// Get plugin by attester type
    fn get_plugin_use_attester_type(&self, attester_type: &String) -> Result<Arc<dyn ServicePlugin>, AttestationError> {
        match PluginManager::<dyn ServicePlugin, ServiceHostFunctions>::get_instance().get_plugin(attester_type) {
            Some(plugin) => Ok(plugin),
            None => Err(AttestationError::PluginNotFoundError({
                error!("Plugin not found for attester type: {}", attester_type);
                format!("Plugin not found for attester type: {}", attester_type)
            })),
        }
    }

    /// Verify evidence using the appropriate plugin
    async fn verify_evidence(
        &self,
        user_id: &str,
        node_id: Option<String>,
        evidence: &Evidence,
        nonce_bytes: Option<Vec<u8>>,
    ) -> Result<serde_json::Value, AttestationError> {
        info!("Starting evidence verification for user: {}, node: {:?}", user_id, node_id);
        let attester_type = &evidence.attester_type;
        let plugin = self.get_plugin_use_attester_type(attester_type)?;

        plugin.verify_evidence(user_id, node_id.as_deref(), &evidence.evidence, nonce_bytes.as_deref()).await.map_err(
            |e| {
                error!("Evidence verification failed: {}", e);
                e.into()
            },
        )
    }
}

impl AttestationHandler for EvidenceVerificationHandler {
    fn handle<'a>(&'a self, context: &'a mut AttestationContext) -> Pin<Box<dyn Future<Output = Result<(), AttestationError>> + Send + 'a>> {
        Box::pin(async move {
            let verification_result = self.verify_evidence(
                &context.user_id,
                Some(context.measurement.node_id.clone()),
                &context.evidence,
                context.aggregate_nonce_bytes.clone(),
            ).await?;
            
            // Store verification result in context
            context.verify_evidence = Some(verification_result);
            Ok(())
        })
    }
    
    fn set_next(&mut self, next: Box<dyn AttestationHandler>) {
        self.next = Some(next);
    }
    
    fn get_next(&self) -> Option<&dyn AttestationHandler> {
        self.next.as_ref().map(|h| h.as_ref())
    }
    
    fn name(&self) -> &'static str {
        "EvidenceVerification"
    }
}